package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.myapplication.R;
import com.example.myapplication.adapter.ViewPagerAdapter;


public class ViewPagerActivity extends AppCompatActivity {

    int[] images = new int[] {R.drawable.banner1, R.drawable.banner2, R.drawable.banner3};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager);

        ViewPagerAdapter viewPagerAdapter =
                new ViewPagerAdapter(this, images);

        // 关联ViewPager
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(viewPagerAdapter);       // 设置adapter

        // 设置圆点
        RadioGroup radioGroup = findViewById(R.id.radio_group);
        for(int i=0; i<images.length; i++) {
            // 动态生成radiobutton组件，放入到radiogroup当中
            RadioButton radioButton = new RadioButton(this);
            radioGroup.addView(radioButton);
        }
        ((RadioButton)radioGroup.getChildAt(0)).setChecked(true);  // 默认选中第一个

        // viewPager滑动事件
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 改变单选框的选中
                ((RadioButton)radioGroup.getChildAt(position)).setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                viewPager.setCurrentItem(checkedId-1);
            }
        });
    }
}